package com.junsi.web.core.config;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.junsi.common.utils.security.AESOperator;

import javax.xml.soap.SOAPException;
import java.util.List;

/**
 * @author anqi
 * @version 1.0
 * @desc webservice 鉴权
 * @date 2019/5/21
 * @see
 * @since 1.0
 */
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
//	Logger logger = LoggerFactory.getLogger(this.getClass());
	// TODO: 2019/5/22  配置
	private static final String USERNAME="admin";
	private static final String PASSWORD="admin";

	public AuthInterceptor() {
		//定义在哪个阶段进行拦截
		super(Phase.PRE_PROTOCOL);
	}

	@Override
	public void handleMessage(SoapMessage soapMessage) throws Fault {
		List<Header> headers = null;
		String username=null;
		String password=null;
		try {
			headers = soapMessage.getHeaders();
		} catch (Exception e) {
//			logger.error("getSOAPHeader error: {}",e.getMessage(),e);
		}

		if (headers == null) {
			throw new Fault(new IllegalArgumentException("找不到Header，无法验证用户信息"));
		}


		//获取用户名,密码
		for (Header header : headers) {
			SoapHeader soapHeader = (SoapHeader) header;
			Element e = (Element) soapHeader.getObject();
			if(null != e && null != e.getTagName()){
				if("username" == e.getTagName()){
					username= e.getTextContent();
				}
				if("password" == e.getTagName()){
					password= e.getTextContent();
				}
			}
		}
		if( StringUtils.isEmpty(username)|| StringUtils.isEmpty(password)){
			throw new Fault(new IllegalArgumentException("用户信息为空"));
		}

		// TODO: 2019/5/22  配置
		AESOperator aesOper = new AESOperator("zbcdef0123456789");
		//校验用户名密码
		try {
			if(!(username.equals(USERNAME) && aesOper.decrypt(password).equals(PASSWORD))){
				SOAPException soapExc = new SOAPException("认证失败");
	//			logger.debug("用户认证信息错误");
				throw new Fault(soapExc);
			}
		} catch (Exception e) {
			e.printStackTrace();
			SOAPException soapExc = new SOAPException("认证失败");
			//			logger.debug("用户认证信息错误");
			throw new Fault(soapExc);
		}

	}

}